package com.liebaut.controller.person;

import com.liebaut.controller.CrudController;
import com.liebaut.dao.person.CustomerRepository;
import com.liebaut.model.person.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

import static com.liebaut.dao.util.CustomerSpecifications.searchCustomer;

@Controller
@RequestMapping("/customer")
public class CustomerController extends CrudController<Customer, Long> {

    public CustomerController() {
    }

    @Autowired
    public CustomerController(CustomerRepository repository) {
        super(repository);
    }

    @Override
    public Iterable list(HttpServletRequest request) {
        String number = request.getParameter("number");
        String name = request.getParameter("name");
        String extraName = request.getParameter("extraName");
        String pageNumber = request.getParameter("page");
        if(name != null || extraName != null){
            Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "number"));
            return ((CustomerRepository)repository).findAll(searchCustomer(name, extraName, number), new PageRequest(pageNumber != null ? Integer.parseInt(pageNumber) : 0 ,10, sort));
        }
        if(number == null || "".equals(number))
            return super.list(request);
        else
            return ((CustomerRepository)repository).findByNumber(number);
    }
}
